package com.guard.ui;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

import com.guard.R;
import com.guard.android.GuardManager;
import com.guard.net.HttpConnectionError;

public class RegisterActivity extends AbstractActivity {
    private final int PHONE_FIELD_LENGTH = 10;
    private final int SMS_CODE_FIELD_LENGTH = 4;
    private Button sendPhoneNumberButton;
    private EditText phoneField;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.registration_activity);
    }

    @Override
    protected void onResume() {
        super.onResume();
        init();
    }

    private void init() {
        sendPhoneNumberButton = (Button) findViewById(R.id.send_register_phone_number);
        phoneField = (EditText) findViewById(R.id.number_field);
        phoneField.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                }
            }
        });
        sendPhoneNumberButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (getCheckedTelNumber(phoneField) == null) {
                    showToast(getString(R.string.phone_number_error_message));
                } else {
                    new AsyncTask<Void, Boolean, Boolean>() {

                        private Exception mException = null;

                        protected void onPreExecute() {
                            InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                            mgr.hideSoftInputFromWindow(phoneField.getWindowToken(), 0);
                            getProgressBar().setVisibility(View.VISIBLE);
                            sendPhoneNumberButton.setEnabled(false);
                        };

                        @Override
                        protected Boolean doInBackground(Void... params) {
                            Boolean result = Boolean.FALSE;
                            GuardManager.instance().setPhoneNumber(getCheckedTelNumber(phoneField));
                            try {
                                result = GuardManager.instance().registerUserPhone(getCheckedTelNumber(phoneField));
                            } catch (HttpConnectionError e) {
                                mException = e;
                            }

                            return result;
                        }

                        protected void onPostExecute(Boolean result) {
                            getProgressBar().setVisibility(View.GONE);
                            sendPhoneNumberButton.setEnabled(true);

                            if (result) {
                                initSMSLayout();
                            }

                            if (mException != null) {
                                showConnectionErrorDialog();
                            }
                        };

                    }.execute((Void) null);
                }
            }
        });
    }

    private String getCheckedTelNumber(EditText field) {
        String text = field.getText().toString();
        if (text.length() == 0) {
            return null;
        }
        if (text.length() != PHONE_FIELD_LENGTH) {
            return null;
        }
        try {
            Double.parseDouble(text);
        } catch (NumberFormatException e) {
            return null;
        }
        return text;
    }

    private String getCheckedSmsCode(EditText field) {
        String text = field.getText().toString();
        if (text.length() == 0) {
            return null;
        }
        if (text.length() != SMS_CODE_FIELD_LENGTH) {
            return null;
        }
        try {
            Double.parseDouble(text);
        } catch (NumberFormatException e) {
            return null;
        }
        return text;
    }
    
    @Override
    public void onBackPressed() {
        isNeedKillApp = true;
        super.onBackPressed();
    }

    private ProgressBar getProgressBar() {
        return (ProgressBar) findViewById(R.id.register_progressbar);
    }

    private void initSMSLayout() {
        findViewById(R.id.sms_code_layout).setVisibility(View.VISIBLE);
        final EditText smsCodeField = (EditText) findViewById(R.id.sms_code_field);
        smsCodeField.requestFocus();
        InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mgr.showSoftInput(smsCodeField, InputMethodManager.SHOW_IMPLICIT);
        final Button smsButton = (Button) findViewById(R.id.forward_button);
        smsButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (getCheckedSmsCode(smsCodeField) == null) {
                    showToast(getString(R.string.sms_code_error_message));
                } else {
                    GuardManager.instance().setSMSCode(getCheckedSmsCode(smsCodeField));
                    new AsyncTask<Void, Boolean, String>() {

                        private Exception mException;

                        @Override
                        protected void onPreExecute() {
                            super.onPreExecute();
                        }

                        @Override
                        protected String doInBackground(Void... params) {
                            String cookie = null;
                            try {
                                cookie = GuardManager.instance().registerUserSms(getCheckedSmsCode(smsCodeField));
                            } catch (HttpConnectionError e) {
                                mException = e;
                            }
                            return cookie;
                        }

                        @Override
                        protected void onPostExecute(String result) {
                            super.onPostExecute(result);

                            if (result != null) {
                                showToast(getResources().getString(R.string.sms_code_ok_message));
                                GuardManager.instance().setCookie(result);
                                onStartActivity(MainActivity.class, null);
                            } else {
                                if (mException == null) {
                                    showToast(getResources().getString(R.string.sms_code_mistake_message));
                                }
                            }

                            if (mException != null) {
                                showConnectionErrorDialog();
                            }
                        }
                    }.execute((Void) null);
                }
            }
        });
    }

}
